<template>
  <div class="menu_list">
    <a-card>
      <!-- 创建按钮 -->
      <div class="role_title">
        <span>菜单列表</span>
        <a-button type="primary" class="set_up" @click="onSetUpMenu" icon="plus" v-action:add="'menu'">新建</a-button>
      </div>
      <!-- 表格 -->
      <a-table 
        :columns="columns" 
        :data-source="menu_list" 
        :pagination="false"
        rowKey="id"
        :scroll="{x: true}"
        :loading="table_loading"
        style="margin-top:24px; margin-bottom:5px;"
      >
        <span slot="action" slot-scope="row">
          <a v-action:edit="'menu'" @click="onUpdateMenu(row)">编辑</a>
          <a-divider type="vertical" style="opacity: 0;" />
          <a v-action:delete="'menu'" @click="onDeleteMenu(row)">删除</a>
        </span>
      </a-table>
    </a-card>
    <a-modal v-model="visible" :title="title" @ok="onSubmit" :maskClosable="false" @cancel="onClose" cancelText="取消" okText="保存" :confirmLoading="form.loadingBtn">
      <!-- 表单 -->
      <a-form-model
        ref="ruleForm"
        :model="form.data"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <!-- 菜单名称 -->
        <a-form-model-item label="菜单名" prop="name">
          <a-input v-model="form.data.name"/>
        </a-form-model-item>
        <!-- 报表 -->
        <a-form-model-item label="报表" prop="reportId">
          <a-select v-model="form.data.reportId">
            <a-select-option v-for="item in reportList" :value="item.id" :key="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 菜单排序 -->
        <a-form-model-item label="排序" prop="order">
          <a-input v-model="form.data.order" />
        </a-form-model-item>
        <!-- 菜单上级 -->
        <a-form-model-item label="上级" prop="parent">
          <a-select v-model="form.data.parent">
            <a-select-option :value="0" :key="0">
              无
            </a-select-option>
            <a-select-option :value="item.id" v-for="item in menuList" :key="item.id">
              {{item.name}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from 'vuex';
import { baseMixin } from '@/store/app-mixin';
const columns = [
        { 
          title: '菜单名', 
          dataIndex: 'name', 
        },
        { 
          title: '报表', 
          dataIndex: 'reportId', 
        },
        { title: '序号', dataIndex: 'order' },
        { 
          title: '创建时间', 
          dataIndex: 'createdAt', 
        },
        { 
          title: '更新时间', 
          dataIndex: 'updatedAt', 
        },
        {
          title: '操作',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        }
      ]

  export default {
    name: 'MenuList',
    mixins: [baseMixin],
    data () {
      const verifiyOrder = (rule, values, callback) => {
        if ( values > 0 ) {
          callback()
        } else {
          callback('序号必须为大于0的数字')
        }
      }
      return {
        columns,
        visible: false,
        title: '创建菜单',
        table_loading: false,
        form: {
          data: {
            parent: 0
          },
          loadingBtn: false,
          statusBtn: false,
        },
        rules: {
          name: [
            { 
              required: true, 
              trigger: 'blur',
              message: '菜单名称不能为空' 
            },
            { 
              max: 20,
              trigger: 'blur',
              message: '最大长度限制为20位' 
            }
          ],
          reportId: [
            { 
              required: true,
              trigger: 'change',
              message: '请选择报表' 
            }
          ],
          order: [
            {
              required: true, 
              trigger: 'blur',
              message: '序号为必填项'
            },
            {
              type: Number,
              validator: verifiyOrder,
              trigger: 'blur'
            }
          ]
        },
      }
    },
    watch: {
      // 关闭抽屉清空表单
      visible (val) {
        if (!val) {
          this.form.data = {}
          this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
        }
      }
    },
    computed: {
      ...mapState('menuManage',['menuList', 'reportList']),
      menu_list () {
        return this.menuList.map(menu => {
          if (menu.children && menu.children.length) {
            let arr = {...menu, reportId: this.show_report(menu.reportId), children:[]}
            for (let i=0; i<menu.children.length; i++) {
              arr.children.push({...menu.children[i], reportId: this.show_report(menu.children[i].reportId)})
            }
            return arr
          } else {
            return {...menu, reportId: this.show_report(menu.reportId)}
          }
        })
      }
    },
    mounted () {
      this.onLoadMenuConfig()
    },
    methods: {
      ...mapActions('menuManage', ['getReportList', 'getMenuList', 'addMenuList', 'updateMenuList', 'getUpdateMenuList', 'deleteMenuList']),
      // 保存
      onSubmit () {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.form.statusBtn = true
            this.form.loadingBtn = true
            if ( this.form.data.id ) {
              this.updateMenuList({ ...this.form.data })
                .then(res => {
                  this.visible = false
                  this.$message.success('菜单修改成功')
                  this.getMenuList()
                })
                .catch(err => this.$message.error('菜单修改失败，原因' +  err.msg  + '！'))
                .finally(() => {
                  this.form.loadingBtn = false
                  this.form.statusBtn = false
                  
                })
            } else {
              this.addMenuList({ ...this.form.data })
                .then(res => {
                  this.visible = false
                  this.$message.success('菜单创建成功')
                  this.getMenuList()
                })
                .catch(err => this.$message.error('菜单创建失败，原因' +  err.msg  + '！'))
                .finally(() => {
                  this.form.loadingBtn = false
                  this.form.statusBtn = false
                })
            }
          } else {
            setTimeout(()=>{
              this.form.loadingBtn = false
              this.form.statusBtn = false
              return false
            },1500)
          }
        })
      },
      show_report (reportId) {
        let name = ''
        this.reportList.forEach(report => {
          if (reportId == report.id){
            name = report.name
          }
        })
        return name
      },
      // 创建
      onSetUpMenu () {
        this.visible = true
        this.title = '创建菜单'
      },
      // 关闭抽屉
      onClose () {
        this.visible = false
      },
      // 获取修改行
      onUpdateMenu (row) {
        this.title='修改菜单'
        this.visible = true
        this.getUpdateMenuList(row.id)
          .then((res) => {
            this.form.data = {...res.data}
          })
          .catch((err) => this.$message.error('获取修改菜单信息失败，原因：'+ err.msg +'！'))
      },
      // 获取删除行
      onDeleteMenu (row) {
        this.$confirm({
          title: '删除提示',
          content: '删除菜单信息无法恢复，您确定要继续吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.deleteMenuList(row.id)
            .then(()=>{
              this.$message.success('菜单删除成功')
              this.getMenuList()
            })
            .catch((err) => {
              this.$message.error('菜单删除失败，原因：'+ err.msg +'！')
            })
          },
          onCancel: () => {},
        })
      },
      // 初始化加载页面数据
      onLoadMenuConfig () {
        this.table_loading = true;
        this.getMenuList()
          .then(res =>{})
          .catch(err =>{
            if (err.code == 401) {
              this.err401(err)
              return
            }
            this.$message.error('获取菜单列表失败，原因：' +  err.msg  + '！')
          })
          .finally(res => {
            this.table_loading = false;
            this.getReportList()
          })
      }
    }
  }
</script>

<style scoped>
.menu_list{
  width: 100%;
  height: 100%;
}
.set_up{
  float: right;
}

.ant-drawer>>>.ant-drawer-body{
  height: calc(100% - 55px);
}

.ant-form{
  height: 100%;
  display: flex;
  flex-direction: column;
}

.submit_style{
  margin-bottom: 0;
  flex: 1;
}

.submit_style>>>.ant-col.ant-col-18.ant-form-item-control-wrapper{
  width: 100%;
  height: 100%;
}

.submit_style>>>.ant-form-item-control{
  display: flex;
  height: 100%;
  align-items: flex-end;
}

.submit_style>>>span.ant-form-item-children{
  width: 100%;
}

.save_button,
.cancal_button {
  float: right;
}

.cancal_button {
  margin-right: 15px;
}

.role_title{
  display: flex;
  justify-content: space-between;
}


.role_title span {
  display: block;
  float: left;
  margin-bottom: 0;
  padding-right: 12px;
  color: rgba(0,0,0,.85);
  font-weight: 500;
  font-size: 16px;
  line-height: 32px;
}

.ant-table-wrapper>>>td.ant-table-row-cell-break-word {
  padding: 10px;
}
</style>
<style>
.ant-modal-body {
  padding: 24px 24px 24px 16px !important;
}

.ant-modal {
  top: 25px;
}

</style>